use chrono;
use log::info;
use ssh2::Session;
use std::io::Read;
use std::net::TcpStream;

pub async fn download_remote_log(
    host: &str,
    port: u16,
    remote_path: &str,
    prefix: Option<&str>,
) -> Result<(), Box<dyn std::error::Error>> {
    info!("开始从 {}:{} 下载日志文件", host, port);

    // Connect to the remote host
    let tcp = TcpStream::connect(format!("{}:{}", host, port))
        .map_err(|e| format!("连接失败: {}", e))?;
    
    let mut sess = Session::new()
        .map_err(|e| format!("创建SSH会话失败: {}", e))?;
    sess.set_tcp_stream(tcp);
    sess.handshake()
        .map_err(|e| format!("SSH握手失败: {}", e))?;

    // Try authentication methods
    let auth_result = sess.userauth_agent("root")
        .or_else(|_| sess.userauth_password("root", "orangepi"));
    
    if let Err(e) = auth_result {
        return Err(format!("认证失败: {}", e).into());
    }

    // Create SFTP session
    let sftp = sess.sftp()
        .map_err(|e| format!("创建SFTP会话失败: {}", e))?;

    // Open the remote file
    let mut remote_file = sftp.open(std::path::Path::new(remote_path))
        .map_err(|e| format!("打开远程文件失败: {}", e))?;

    // Create local file with timestamp
    let timestamp = chrono::Local::now().format("%Y%m%d_%H%M%S");
    // 使用传入的前缀或默认值
    let file_prefix = prefix.unwrap_or("orangepi-cli");
    let local_path = format!("{}_{}.log", file_prefix, timestamp);
    let mut local_file = std::fs::File::create(&local_path)
        .map_err(|e| format!("创建本地文件失败: {}", e))?;

    // Copy the contents
    let mut contents = Vec::new();
    remote_file.read_to_end(&mut contents)
        .map_err(|e| format!("读取远程文件失败: {}", e))?;
    
    std::io::copy(&mut contents.as_slice(), &mut local_file)
        .map_err(|e| format!("写入本地文件失败: {}", e))?;

    info!("日志文件已成功下载到: {}", local_path);
    Ok(())
}